<template>
<div>
    <div class="carousel" @mouseenter="killInter" @mouseleave="CreateInter">
        <div class="carousel-inner" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
            <div class="carousel-item" v-for="(item, index) in items" :key="index">
                <img :src="item" alt="Carousel Image" />
            </div>
        </div>
        <button class="prev" @click="prev">❮</button>
        <button class="next" @click="next">❯</button>
    </div>
</div>
</template>

<script setup>
    import {onMounted, onUnmounted, ref} from "vue";
    import {getjournalismRanking} from "@/api/request.js";

    const items = ref([]);
    const currentIndex = ref(0);

    async function getMessages() {
      let message = (await getjournalismRanking()).records
      if(message.length > 0){
        for(let i = 0;i < message.length;i++){
          if(message[i].imageSrc!==null){
            items.value.push(message[i].imageSrc)
          }
        }
      }
    }
    getMessages()
    // 定义 next 方法
    function next(){
        currentIndex.value = (currentIndex.value + 1) % items.value.length;
    }
    // 定义 prev 方法
    function prev() {
        currentIndex.value = (currentIndex.value - 1 + items.value.length) % items.value.length;
    }

    onMounted(CreateInter)
    onUnmounted(killInter)
    let interNumber=[]
    function CreateInter() {
        let intervalId = setInterval(next, 3000);
        interNumber.push(intervalId)
    }
    function killInter() {
        for (let i = 0; i < interNumber.length; i++) {
            clearInterval(interNumber[i])
        }
    }
</script>

<style scoped>
    .carousel {
        position: relative;
        width: 300px;
        height: 300px;
        overflow: hidden;
        margin-left: 7px;
        margin-top: 16px
    }

    .carousel-inner {
        display: flex;
        transition: transform 0.5s ease;
    }

    .carousel-item {
        min-width: 100%;
        height: 300px;
    }

    .carousel-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    button {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(255, 255, 255, 0.7);
        border: none;
        cursor: pointer;
    }

    .prev {
        left: 5px;
    }

    .next {
        right: 5px;
    }
</style>